import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/apartment/api.dart";
import "package:ct_pa_majordomo/pages/check_in_detail/check_in_info_state.dart";
import "package:ct_pa_majordomo/pages/check_in_detail/detail/widgets/cohabitant/index.dart";
import "package:ct_pa_majordomo/pages/check_in_detail/detail/widgets/edit_remark/index.dart";
import "package:ct_pa_majordomo/pages/check_in_detail/detail/widgets/rent_info/index.dart";
import "package:ct_pa_majordomo/pages/check_in_detail/detail/widgets/renter_info/index.dart";
import "package:ct_pa_majordomo/pages/check_in_detail/widgets/info_block.dart";
import "package:ct_pa_majordomo/pages/check_in_detail/widgets/info_item.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:ct_pa_majordomo/utils/index.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/divider/solid_divider.dart";
import "package:ct_pa_majordomo/widgets/show_datetime_picker.dart";
import "package:ct_pa_majordomo/widgets/tai_dialog/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";

import "../../main.dart";

class Detail extends StatefulWidget {
  final Map info;
  final Map mainRenter;
  const Detail({super.key, required this.info, required this.mainRenter});

  @override
  State<StatefulWidget> createState() => _DetailState();

}

class _DetailState extends State<Detail> {

  final GlobalKey _key = GlobalKey();

  final Map _rentTypeDict = {
    1: "每1月",
    2: "每2月",
    3: "每3月",
    4: "每4月",
    5: "每半年",
    6: "每一年",
    7: "一次性",
  };
  Map? _info;
  Map? _mainRenter;
  List? _cohabitants;

  @override
  void initState() {
    super.initState();
  }

  @override
  void didChangeDependencies() {
    _info = CheckInInfoState.of(context)?.info;
    _mainRenter = CheckInInfoState.of(context)?.mainRenter;
    _cohabitants = CheckInInfoState.of(context)?.cohabitants;
    super.didChangeDependencies();
  }

  String _rentTypeValue () {
    if (Utils.isEmpty(_info?["rentObject"]) || _info?["rentObject"]?["rentType"] == -1) {
      return "--";
    }
    return _rentTypeDict[_info?["rentObject"]?["rentType"]];
  }

  void changeInfo() {
    CheckInInfoState.of(context)?.getCheckInInfo();
  }

  Widget _renderVerifyStatus(int? status) {
    if (status == null) return const SizedBox();
    
    return Container(
      margin: const EdgeInsets.only(left: 4),
      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
      decoration: BoxDecoration(
        color: status == 1 ? ThemeVars.colorSuccess.withOpacity(0.1) : ThemeVars.colorWarning.withOpacity(0.1),
        borderRadius: BorderRadius.circular(2),
      ),
      child: Text(
        status == 1 ? "已认证" : "未认证",
        style: TextStyle(
          fontSize: 12,
          color: status == 1 ? ThemeVars.colorSuccess : ThemeVars.colorWarning,
        ),
      ),
    );
  }

  Widget _renderDetail() {
    return CustomScrollView(
      key: PageStorageKey<String>("入住详情"),
      slivers: <Widget>[
        SliverOverlapInjector(
          // This is the flip side of the SliverOverlapAbsorber
          // above.
          handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
        ),
        SliverPadding(
            padding: const EdgeInsets.fromLTRB(0, 0, 0, 52),
            sliver: SliverToBoxAdapter(
                child: Column(
                  children: <Widget>[
                    InfoBlock(
                      title: "入住信息",
                      actions: [
                        TextButton(
                          onPressed: () {
                            Map renterInfo = {
                              "renterId": _mainRenter?["renterId"],
                              "name": _mainRenter?["name"],
                              "contacts": _mainRenter?["contacts"],
                              "idCardNumber": _mainRenter?["idCardNumber"],
                              "checkInStart": _info?["checkInStart"],
                              "checkInEnd": _info?["checkInEnd"],
                              "checkInId": _info?["checkInId"],
                              "picUrl": _mainRenter?["picUrl"],
                              "verifyStatus": _mainRenter?["verifyStatus"],
                            };
                            Stacker.pushNamed(
                              Keys.CHECK_IN_DETAIL_RENTER_INFO,
                              arguments: {
                                "info": renterInfo,
                                "renterType": RenterType.renter,
                                "changeInfo": changeInfo,
                              },
                            );
                          },
                          child: const Text("编辑"),
                        ),
                      ],
                      children: [
                        InfoItem(
                          label: "姓名", 
                          value: "",
                          customValue: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Text(_mainRenter?["name"] ?? ""),
                              _renderVerifyStatus(_mainRenter?["verifyStatus"]),
                            ],
                          ),
                        ),
                        InfoItem(label: "联系方式", value: _mainRenter?["contacts"] ?? ""),
                        InfoItem(label: "证件号", value: _mainRenter?["idCardNumber"] ?? "--"),
                        InfoItem(label: "入住周期", value: "${_info?["checkInStart"]} 至 ${_info?["checkInEnd"]}"),
                      ],
                    ),
                    const SizedBox(height: 10,),
                    InfoBlock(
                      title: "同住人信息",
                      actions: [
                        TextButton(
                          onPressed: () {
                            Stacker.pushNamed(
                              Keys.CHECK_IN_DETAIL_COHABITANT,
                              arguments: {
                                "checkInId": _info?["checkInId"],
                                "changeInfo": changeInfo,
                              },
                            );
                          },
                          child: const Text("添加"),
                        ),
                      ],
                      children: _cohabitants != null ? List.generate(_cohabitants!.length * 2, (index) {
                        if (index.isOdd) {
                          return const SolidDivider();
                        }
                        Map cohabitants = _cohabitants?[index ~/ 2];
                        return Column(
                          children: [
                            InfoItem(
                              label: "姓名",
                              value: "",
                              customValue: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Text(cohabitants["name"]),
                                  _renderVerifyStatus(cohabitants["verifyStatus"]),
                                ],
                              ),
                            ),
                            InfoItem(label: "联系方式", value: cohabitants["contacts"]),
                            InfoItem(
                              label: "证件号",
                              value: cohabitants["idCardNumber"],
                              suffix: GestureDetector(
                                onTap: () {
                                  Map renterInfo = {
                                    "renterId": cohabitants["renterId"],
                                    "name": cohabitants["name"],
                                    "contacts": cohabitants["contacts"],
                                    "idCardNumber": cohabitants["idCardNumber"],
                                    "checkInId": _info?["checkInId"],
                                    "picUrl": cohabitants["picUrl"],
                                    "verifyStatus": cohabitants["verifyStatus"],
                                  };
                                  Map<String, dynamic> arguments = {
                                    "changeInfo": changeInfo,
                                    "info": renterInfo,
                                    "renterType": RenterType.cohabitant
                                  };
                                  Stacker.pushNamed(Keys.CHECK_IN_DETAIL_RENTER_INFO, arguments: arguments);
                                },
                                child: const Padding(
                                    padding: EdgeInsets.symmetric(horizontal: 18),
                                    child: Text("编辑", style: TextStyle(color: ThemeVars.colorPrimary, fontSize: 14),)
                                ),
                              ),
                            ),
                          ],
                        );
                      }) : []
                    ),
                    const SizedBox(height: 10,),
                    InfoBlock(
                      title: "房租信息",
                      actions: [
                        TextButton(
                          onPressed: () {
                            Stacker.pushNamed(
                              Keys.CHECK_IN_DETAIL_RENT_INFO,
                              arguments: {
                                "checkInId": _info?["checkInId"],
                                "rentObject": _info?["rentObject"],
                                "changeInfo": changeInfo,
                              },
                            );
                          },
                          child: const Text("编辑"),
                        ),
                      ],
                      children: Utils.isNotEmpty(_info?["rentObject"]) ? [
                        InfoItem(label: "月租金", value: "${_info?["rentObject"]?["rent"] ?? "--"}"),
                        InfoItem(label: "押金", value: "${_info?["rentObject"]?["deposit"] ?? "--"}"),
                        InfoItem(label: "付款方式", value: _rentTypeValue() ),
                      ] : [],
                    ),
                    const SizedBox(height: 10,),
                    InfoBlock(
                      title: "备注",
                      actions: [
                        TextButton(
                          onPressed: () {
                            Stacker.pushNamed(
                              Keys.CHECK_IN_DETAIL_EDIT_REMARK,
                              arguments: {
                                "checkInId": _info?["checkInId"],
                                "remark": _info?["remark"],
                                "changeInfo": changeInfo,
                              },
                            );
                          },
                          child: const Text("编辑"),
                        ),
                      ],
                      content: Utils.isNotEmpty(_info?["remark"]) ? Container(
                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                        decoration: const BoxDecoration(
                          borderRadius: BorderRadius.all(Radius.circular(3)),
                          color: ThemeVars.colorBackground,
                        ),
                        child: Text(_info?["remark"] ?? "", textAlign: TextAlign.left,),
                      ) : null,
                    ),
                    // const SizedBox(height: 10,),
                    // InfoBlock(
                    //   title: "视频图片",
                    //   actions: [
                    //     TextButton(
                    //       onPressed: () {},
                    //       child: const Text("编辑"),
                    //     ),
                    //   ],
                    // ),
                    Padding(
                      padding: EdgeInsets.all(ThemeVars.paddingPage),
                      child: Text("入住操作：${_info?["createBy"]} ${DateTools.formatYMD(_info?["createTime"], format: "{y}-{m}-{d} {h}:{i}")}", style: TextStyle(color: ThemeVars.colorTextTer, fontSize: 12),),
                    ),
                  ],
                )
            )
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      key: _key,
      top: false,
      bottom: false,
      child: Stack(
        children: [
          Builder(
            builder: (BuildContext context) {
              return _renderDetail();
            },
          ),
          Positioned(
            left: 0,
            bottom: 0,
            width: MediaQuery.of(context).size.width,
            child: Container(
              decoration: const BoxDecoration(
                color: Colors.white,
              ),
              padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              child: Row(
                children: [
                  Expanded(
                    child: Button(
                      onPressed: () {
                        showDatetimePicker(
                          context: context,
                          initialDateTime: DateTime.parse(_info?["checkInEnd"]).add(const Duration(days: 1)),
                          minimumDate: DateTime.parse(_info?["checkInEnd"]).add(const Duration(days: 1)),
                          onchange: (value) async {
                            print("时间是：》》》$value");
                            Map<String, dynamic> params = {
                              "checkInId": _info?["checkInId"],
                              "checkInEnd": DateTools.formatTime(value.millisecondsSinceEpoch, format: "{y}-{m}-{d}"),
                            };
                            await apartmentApi.updateCheckIn(params);
                            EasyLoading.showSuccess("续租成功");
                            // Stacker.popUntil(ModalRoute.withName(Keys.MAIN));
                            Stacker.pushAndRemoveUntil(const Main(index: 1,));
                          }
                        );
                      },
                      child: const Text("续租"),
                    ),
                  ),
                  SizedBox(width: 12,),
                  Expanded(
                    child: Button(
                      type: ButtonType.primaryOutline,
                      onPressed: () {
                        taiDialog(
                          context: context,
                          child: const Text("确定办理退房？", textAlign: TextAlign.center,),
                          onConfirm: (taiContext) async {
                            await apartmentApi.checkOut(_info?["checkInId"]);
                            EasyLoading.showSuccess("退房成功");
                            Stacker.pushAndRemoveUntil(const Main(index: 1,));
                          }
                        );
                      },
                      child: const Text("退房"),
                    ),
                  )
                ],
              ),
            )
          ),
        ],
      ),
    );
  }

}